<template>
  <div class="category-container">
    <div class="container">
      <!-- 分类标题 -->
      <div class="category-header">
        <h1>{{ currentCategory.name }}</h1>
        <div class="filter-options">
          <el-radio-group v-model="sortType" size="small" @change="handleSort">
            <el-radio-button label="default">默认排序</el-radio-button>
            <el-radio-button label="latest">最新发布</el-radio-button>
            <el-radio-button label="popular">最多播放</el-radio-button>
            <el-radio-button label="like">最多点赞</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 分类筛选器 -->
      <div class="category-filter">

        <div class="filter-tags">
          <el-tag 
            v-for="type in videoTypes" 
            :key="type.type_id"
            :type="selectedTypeId === type.type_id ? 'primary' : ''"
            :closable="selectedTypeId === type.type_id"
            @click="selectType(type.type_id)"
            @close="clearType"
          >
            {{ type.type_name }}
          </el-tag>
        </div>
      </div>

      <!-- 视频列表 -->
      <div class="video-list" v-if="!loading">
        <el-card 
          v-for="video in filteredVideos" 
          :key="video.video_id"
          class="video-card"
          @click="goToVideoDetail(video.video_id)"
        >
          <div class="video-cover">
            <img 
              :src="video.video_cover || '/placeholder.svg?size=300x180'" 
              :alt="video.video_title"
              class="cover-image"
            >
            <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count }}</span>
          </div>
          <div class="video-info">
            <h3 class="video-title">{{ video.video_title }}</h3>
            <div class="video-meta">
              <span class="author">{{ getUserName(video.user_id) }}</span>
              <div class="video-stats">
                <span><el-icon><StarFilled /></el-icon> {{ video.like_count }}</span>
                <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
                <span>{{ formatTime(video.video_time) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <el-empty v-else description="加载中..." class="loading-container" />

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="!loading && filteredVideos.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          :page-sizes="[12, 24, 48, 96]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredVideos.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 无内容提示 -->
      <el-empty v-if="!loading && filteredVideos.length === 0" description="暂无相关视频" class="empty-container" />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useVideoStore } from '../store/videoStore'
import { View, StarFilled, ChatDotRound } from '@element-plus/icons-vue'
import { ElCard, ElTag, ElRadioGroup, ElRadioButton, ElPagination, ElEmpty } from 'element-plus'

export default {
  name: 'CategoryView',
  components: {
    ElCard,
    ElTag,
    ElRadioGroup,
    ElRadioButton,
    ElPagination,
    ElEmpty,
    View,
    StarFilled,
    ChatDotRound
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const videoStore = useVideoStore()
    
    const sortType = ref('default')
    const selectedTypeId = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(12)
    const commentsMap = ref({})

    onMounted(async () => {
      await initPage()
    })

    watch(() => route.params.id, async () => {
      await initPage()
    })

    const initPage = async () => {
      console.log('初始化页面...')
      console.log('路由参数:', route.params)
      const categoryId = parseInt(route.params.id)
      console.log('解析后的分类ID:', categoryId)
      if (!isNaN(categoryId)) {
        selectedTypeId.value = categoryId
        console.log('设置selectedTypeId:', selectedTypeId.value)
      }
      
      console.log('加载数据前的videoTypes:', videoStore.videoTypes)
      await Promise.all([
        videoStore.fetchVideos(),
        videoStore.fetchVideoTypes(),
        loadComments()
      ])
      
      console.log('加载数据后的videoTypes:', videoStore.videoTypes)
      console.log('初始化完成后的selectedTypeId:', selectedTypeId.value)
      currentPage.value = 1 // 重置页码
    }

    const loadComments = async () => {
      try {
        const comments = await fetch('http://localhost:3001/comments')
        const data = await comments.json()
        // 统计每个视频的评论数
        data.forEach(comment => {
          if (!commentsMap.value[comment.video_id]) {
            commentsMap.value[comment.video_id] = 0
          }
          commentsMap.value[comment.video_id]++
        })
      } catch (error) {
        console.error('加载评论统计失败:', error)
      }
    }

    const handleSort = () => {
      currentPage.value = 1 // 排序变化时重置页码
    }

    const selectType = (typeId) => {
      selectedTypeId.value = typeId
      currentPage.value = 1 // 筛选变化时重置页码
      if (route.path !== `/category/${typeId}`) {
        router.push(`/category/${typeId}`)
      }
    }

    const clearType = () => {
      selectedTypeId.value = null
      currentPage.value = 1
      router.push('/category/all')
    }

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
    }

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
    }

    const goToVideoDetail = (videoId) => {
      router.push(`/video/${videoId}`)
    }

    const getUserName = (userId) => {
      const userMap = {
        1: '张三',
        2: '李四',
        3: '王五',
        4: '赵六',
        5: '测试用户1',
        6: '测试用户2'
      }
      return userMap[userId] || '未知用户'
    }

    const getCommentCount = (videoId) => {
      return commentsMap.value[videoId] || 0
    }

    const formatTime = (timeString) => {
      const date = new Date(timeString)
      return date.toLocaleDateString('zh-CN')
    }

    // 计算属性
    const videoTypes = computed(() => videoStore.videoTypes)
    const loading = computed(() => videoStore.loading)
    
    const currentCategory = computed(() => {
      console.log('Selected Type ID:', selectedTypeId.value)
      // 使用硬编码的视频类型映射，确保分类名称正确显示
      const categoryMap = {
        1: '科技',
        2: '游戏',
        3: '美食',
        4: '数码',
        5: '音乐',
        6: '旅行'
      }
      
      if (!selectedTypeId.value) {
        return { name: '所有视频' }
      }
      
      const categoryName = categoryMap[selectedTypeId.value]
      console.log('获取到的分类名称:', categoryName)
      return { name: categoryName || '未知分类' }
    })

    const filteredVideos = computed(() => {
      let videos = [...videoStore.videos]
      
      // 按类型筛选
      if (selectedTypeId.value) {
        videos = videos.filter(video => video.type_id === selectedTypeId.value)
      }
      
      // 排序
      switch (sortType.value) {
        case 'latest':
          videos.sort((a, b) => new Date(b.video_time) - new Date(a.video_time))
          break
        case 'popular':
          videos.sort((a, b) => (b.view_count || 0) - (a.view_count || 0))
          break
        case 'like':
          videos.sort((a, b) => (b.like_count || 0) - (a.like_count || 0))
          break
        default:
          // 默认排序（可以按其他逻辑）
          break
      }
      
      // 分页
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return videos.slice(start, end)
    })

    return {
      sortType,
      selectedTypeId,
      currentPage,
      pageSize,
      videoTypes,
      loading,
      currentCategory,
      filteredVideos,
      videoStore,  // 添加这一行
      handleSort,
      selectType,
      clearType,
      handleSizeChange,
      handleCurrentChange,
      goToVideoDetail,
      getUserName,
      getCommentCount,
      formatTime
    }
  }
}
</script>

<style scoped>
.category-container {
  background: var(--bg-primary);
  min-height: calc(100vh - 60px);
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #00b42a;
}

.category-header h1 {
  margin: 0;
  font-size: 24px;
  color: #000000;
}

.filter-options {
  display: flex;
  gap: 10px;
}

.category-filter {
  background: var(--bg-card);
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
  border: 1px solid var(--border-color);
}

.filter-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 10px;
}

.filter-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.video-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.video-card {
  cursor: pointer;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  background-color: var(--bg-card) !important;
  border-color: var(--border-color) !important;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.video-cover {
  position: relative;
  margin-bottom: 10px;
}

.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.view-count {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.video-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  font-size: 14px;
  color: var(--text-secondary);
}

.author {
  flex: 1;
  margin-right: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--text-secondary);
}

.video-stats {
  display: flex;
  gap: 10px;
}

.video-stats span {
  display: flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
  color: var(--text-disabled);
}

.pagination-wrapper {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.loading-container,
.empty-container {
  padding: 50px 0;
  background: var(--bg-card);
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid var(--border-color);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .video-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .category-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .video-list {
    grid-template-columns: 1fr;
  }
  
  .cover-image {
    height: 180px;
  }
}
</style>